package com.haolijun.eecms.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.haolijun.eecms.common.R;
import com.haolijun.eecms.dao.TbActiveDao;
import com.haolijun.eecms.entity.TbActive;
import com.haolijun.eecms.service.ActiveService;
import com.haolijun.eecms.service.ApplyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ActiveServiceImpl
 * @Description TODO
 * @Author hljstart
 * @Date 2023/3/12 10:14
 * @Version 1.0
 */
@Service
@Slf4j
public class ActiveServiceImpl implements ActiveService {

    @Autowired
    private TbActiveDao activeDao;

    @Autowired
    private ApplyService applyService;

    @Override
    public R searchActiveByPage(HashMap param) {
        // 1、 获取当前页数
        int page = (int) param.get("page");
        // 2、获取每一页的记录数
        int length = (int) param.get("length");
        // 3、计算出当前的要开始的页数
        int start = (page - 1) * length;
        // 4、放入到集合中
        param.put("start", start);
        // 5、设置当前查看用户的id
        int userId = StpUtil.getLoginIdAsInt();
        param.put("userId",userId);
        // 5、获取总记录数
        long count = activeDao.searchActiveCount(param);
        // 获取活动信息
        List<HashMap> actives = activeDao.searchActiveByPage(param);
        // 7、封装参数
        R r = R.ok().data("totalCount", count).data("pageSize", length).data("pageIndex", start).data("actives", actives);
        // 8、返回
        return r;
    }

    @Override
    public int insert(TbActive active) {
        active.setCreateTime(new Date());
        int userId = StpUtil.getLoginIdAsInt();
        active.setUserId(userId);
        int rows = activeDao.insert(active);
        return rows;
    }

    @Transactional
    @Override
    public int delete(Integer id) {
        Map param = new HashMap<String,Integer>();
        param.put("id", id);
        int userId = StpUtil.getLoginIdAsInt();
        param.put("userId",userId);
        int rows = activeDao.delete(param);
        if(rows > 0){
            applyService.deleteApplyByAcid(id);
        }
        return rows;
    }

    @Override
    public HashMap searchActiveInfo(Integer acId) {
        int userId = StpUtil.getLoginIdAsInt();
        Map param = new HashMap();
        param.put("acId", acId);
        param.put("userId", userId);
        // 查看用户是否报名
        int isApply = applyService.searchUserIsApply(param);
        // 查看活动细节
        HashMap map = activeDao.searchActiveInfo(acId);
        map.put("isApply", isApply > 0);
        return map;
    }
}
